package com.ts.api.http.receive.biz;

import com.alibaba.fastjson.JSONObject;
import com.gitee.apanlh.util.algorithm.encrypt.symmetric.DESede;
import com.gitee.apanlh.util.base.ChooseEq;
import com.gitee.apanlh.util.base.MapUtils;
import com.gitee.apanlh.util.base.StringUtils;
import com.gitee.apanlh.util.cache.redis.RedisKeyBuilder;
import com.gitee.apanlh.util.cache.redis.api.RedisString;
import com.gitee.apanlh.util.dataformat.JsonUtils;
import com.gitee.apanlh.util.encode.Base64Type;
import com.gitee.apanlh.util.reflection.CopyUtils;
import com.gitee.apanlh.util.valid.Assert;
import com.gitee.apanlh.util.valid.ValidParam;
import com.gitee.apanlh.web.model.vo.RequestVO;
import com.ts.api.common.constant.api.ApiEnum;
import com.ts.api.common.context.ApiContext;
import com.ts.api.common.entity.ApiParameter;
import com.ts.api.common.util.ApiDictUtils;
import com.ts.api.exp.ApiMsgException;
import com.ts.api.http.receive.entity.apply.req.ApiReceiveDataApplyXAQB;
import com.ts.api.http.receive.entity.dataexchange.req.ApiReceiveDataExchangeMaskXAQB;
import com.ts.api.module.api.convert.core.annotation.ApiReceive;
import com.ts.api.module.api.convert.core.annotation.ApiReceiveConvertType;
import com.ts.api.module.api.convert.receive.entity.ApiReceiveApply;
import com.ts.api.module.api.convert.receive.entity.ApiReceiveDecrypt;
import com.ts.api.module.api.convert.receive.entity.ApiReceiveNotice;
import com.ts.api.module.api.convert.receive.entity.ApiReceivePhoneMaskDataExchange;
import com.ts.api.module.api.convert.receive.handler.ApiReceivePhoneMaskConvertHandler;
import com.ts.api.module.api.entity.ApiUserRequest;

import javax.crypto.spec.DESedeKeySpec;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 名称：小安钱包-15A
 * 版本: URL-V2
 * 文档地址:https://www.showdoc.com.cn/p/12051fcbf925b3aceac69fec51c215e5
 * 文档密码:123321
 * 双方公钥交换，加密
 * <p>
 * COPY 原始文件 ApiReceiveXAQB15.java
 *
 * @date 2025/6/11
 **/
@ApiReceive(apiClientId = "1969054044609466368", type = ApiReceiveConvertType.API_CHANNEL_PHONE_MASK)
public class ApiReceiveMaskJiFenQiV2CPS37 implements ApiReceivePhoneMaskConvertHandler {

//    //  对方公钥
//    public static final String PUBLIC_KEY = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEArae5t3czwLmBGtYskIIrPGQ4U9v/Pa6jSIme9H3kbvn6+xJVma986M/K16QlCSqQlxP4GsiiRR4pAoyCePHG1OjWyj9HWfLTFxY/NNhq0wRTCg7tSo1VCrdTuEkw+AJ29N/4Uw25HvOtOmU4eka646RFDtFQ7vUpuNJUvsWIVvre28rj2NFof/r4X/Xix5ZHPIxQxUmoq1AU2dwdDp/cfzY1zck5Ej8jxESeZv2YsKrQUh8tWmDmEjATCjK7j1CDoKnOXhO4yxLTJqTr+EFlTmk4OJIguBSrzhaRIka5NrJaqSuotOucE6LB3MiNqkFetfDtScxSsJJixinAWbkqHQIDAQAB";
//    //  我方提供公钥
//    public static final String ME_PUBLIC_KEY = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAqrT3UECIRApnt7xUf/WxpyJb/lp2pczMSPD8eSOiu+AE/yEoJzohYQcqwytjyx6FU68TC62kOG50Munn5HbFqFWPSFlXJQ1lUtT6VKNzO+IK39nmWF5ie4phPjv09LQhh61Hb17YRaW223UwN11jLlRQ6JXAa/7vO2uihmTznVpZ60tcI13gIdtzTAHT5IaRpV7lQ6Q2BhQFIFjf289xyOCkWFGR04IvDhFvB5QNTXhCB4cqi9J6iohKL068cpbyc/rxm5LS3SRgFeRLLgvaOabBggjiqJHA26ZQMy+imosVaeR9z2da4gBV4zzuKzA7jGukk5DWK56hcV/p4n5hzwIDAQAB";
//    //  我方私钥
//    public static final String ME_PRIVATE_KEY = "MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQCqtPdQQIhECme3vFR/9bGnIlv+WnalzMxI8Px5I6K74AT/ISgnOiFhByrDK2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cv1muOvpu+l8MHUv1zXMA78aYHHJGDZjNltXxdf8aci3jPUEGHdzq+Y2Q2sECHfZ9d7WLJEpovVyQKBgQCMN453i2lALwaGMhhahNYEneFoZtMvhCR1eMczKFaa73o+V58qT14slvGrmICMaFz3uCUxVUcWyycAVqZTHsioB6eDS6n+zGXttst+meQcdgjxUOTKd4jb4pKh2uOeiUgbpPOBQ9wajU3pNCaPUz1oV9McjyqUbeIdNY3bk3+C3QKBgALf2lS/EnP9eaoseTugjQECAZ047+5nIXbwiGsDaF1Ib8tqX1A+I9eNyXoFJkX6EO1o28vEDAAdwOaz9+5xvFBj74zQYEu/e134fMRYpOmxyKJZUGd2Xuu0OADZN/nchitQotU5Ix/UDJ+vgSMHfjrEMpnUZZdXbfgApsZGQbEg";

    public static final String KEY = "cc17c30cd111c7215fc8f51f8790e0e1";
    public static final String IV = "12345670";

    private static final RedisString TEMP = RedisKeyBuilder.builder().withKeys("com.ts.api.http.receive.biz.ApiReceiveMaskJiFenQiV2CPS37").buildString();

    @Override
    public Map<String, String> requireParam(RequestVO requestVO) throws Exception {
        Assert.isNotEmptyThrows(requestVO.getBody(), new ApiMsgException(ApiEnum.API_BODY_ERROR));

        //  获取请求体参数
        Map<String, Object> map = JsonUtils.toMap(requestVO.getBody());
        String encryption = String.valueOf(map.get("encryption"));
        String planId = String.valueOf(map.get("plan_id"));
        String orderNum = String.valueOf(map.get("order_num"));

        //  传递什么，验证什么Key
        Assert.isNotEmptyThrows(encryption, new ApiMsgException(ApiEnum.API_RECEIVE_BODY_MISS.format("encryption")));
        Assert.isNotEmptyThrows(planId, new ApiMsgException(ApiEnum.API_RECEIVE_BODY_MISS.format("plan_id")));
        Assert.isNotEmptyThrows(orderNum, new ApiMsgException(ApiEnum.API_RECEIVE_BODY_MISS.format("order_num")));

        //  返回需要的数据Map
        return MapUtils.newHashMap(newMap -> {
            ApiParameter apiParameter = ApiContext.PARAMETER.get();
            apiParameter.put("plan_id", map.get("plan_id"));
            apiParameter.put("order_num", map.get("order_num"));

            newMap.put("encryption", encryption);
            newMap.put("plan_id", planId);
            newMap.put("order_num", orderNum);
        });
    }

    @Override
    public ApiReceiveDecrypt decrypt(Map<String, String> paramMap, RequestVO requestVO) throws Exception {
        String encryptData = paramMap.get("encryption");
        DESede cbc = DESede.createCbc(new DESedeKeySpec(KEY.getBytes()).getKey(), IV.getBytes());
        String decrypt = cbc.decryptFromBase64Str(encryptData, Base64Type.RFC2045);
        JSONObject jsonObject = JsonUtils.get(decrypt);
        return new ApiReceiveDecrypt(jsonObject.getString("encryption"));
    }

    @Override
    public ApiUserRequest parseDataExchange(ApiReceiveDecrypt apiReceiveDecryptMessage) throws Exception {
        ApiReceiveDataExchangeMaskXAQB parse = apiReceiveDecryptMessage.parse(ApiReceiveDataExchangeMaskXAQB.class);
        ApiUserRequest apiUserRequest = CopyUtils.copy(parse, ApiUserRequest.class);
        fieldMapping(apiUserRequest);
        return apiUserRequest;
    }

    @Override
    public Map<String, Object> respDataExchange(ApiReceivePhoneMaskDataExchange dataExchangeMessage) throws Exception {
        ApiParameter apiParameter = ApiContext.PARAMETER.get();
        Map<String, Object> resultMap = MapUtils.newLinkedHashMap();
        boolean suc = dataExchangeMessage.hasBizSuc();
        Object orderNum = apiParameter.get("order_num");
        if (!suc) {
            resultMap.put("code", 300);
            resultMap.put("plan_id", apiParameter.get("plan_id"));
            resultMap.put("order_num", orderNum);
            resultMap.put("msg", "客户重复");
            return resultMap;
        }

        resultMap.put("code", 200);
        resultMap.put("msg", "匹配成功");
        resultMap.put("plan_id", apiParameter.get("plan_id"));
        resultMap.put("order_num", orderNum);
        List<Object> list = new ArrayList<>();
        Map<Object, Object> newLinkedHashMap = MapUtils.newLinkedHashMap(dataMap -> {
//            // 公司授权唯一id
//            dataMap.put("company_id", dataExchangeMessage.getReqId());
//            //  价格
//            dataMap.put("price", dataExchangeMessage.getPrice());
//            //  公司名称
//            dataMap.put("company", dataExchangeMessage.getOrgName());
//            //  产品名称
//            dataMap.put("company_name", dataExchangeMessage.getDisplayName());
//            dataMap.put("md5_mobile_list", dataExchangeMessage.getListPhoneMd5());
        });
        list.add(newLinkedHashMap);
        resultMap.put("data", MapUtils.newLinkedHashMap(dataMap -> {
            dataMap.put("list", list);
        }));
        newLinkedHashMap.put("plan_id", apiParameter.get("plan_id"));
        TEMP.setForMinutes(String.valueOf(orderNum), JsonUtils.toJson(newLinkedHashMap), 10);
        return resultMap;
    }

    @Override
    public ApiUserRequest parseApply(ApiReceiveDecrypt apiReceiveDecryptMessage) throws Exception {
        ApiReceiveDataApplyXAQB parse = apiReceiveDecryptMessage.parse(ApiReceiveDataApplyXAQB.class);
        ApiUserRequest apiUserRequest = CopyUtils.copy(parse, ApiUserRequest.class);
        fieldMapping(apiUserRequest);
        return apiUserRequest;
    }

    @Override
    public Map<String, Object> respApply(ApiReceiveApply applyMessage) throws Exception {
        Map<String, Object> resultMap = MapUtils.newLinkedHashMap();
        boolean suc = applyMessage.hasBizSuc();
        if (!suc) {
            resultMap.put("code", 300);
            resultMap.put("msg", "进件失败");
            return resultMap;
        }

        resultMap.put("code", 200);
        resultMap.put("msg", "进件成功");
        return resultMap;
    }

//    /**
//     * 加签
//     *
//     * @param privateKeyString 我方私钥
//     * @param content          原文
//     * @return 签文
//     * @throws Exception
//     */
//    private String rsaSign(String privateKeyString, String content) throws Exception {
//        KeyFactory keyFactory = KeyFactory.getInstance("RSA", new BouncyCastleProvider());
//        PKCS8EncodedKeySpec priPKCS8 = new PKCS8EncodedKeySpec(Base64Utils.decode(privateKeyString));
//        PrivateKey privateKey = keyFactory.generatePrivate(priPKCS8);
//        Signature signature = Signature.getInstance("SHA256WITHRSA");
//        signature.initSign(privateKey);
//        signature.update(content.getBytes());
//        return new String(Base64Utils.encode(signature.sign()));
//    }
//
//    /**
//     * 验签
//     *
//     * @param publicKeyString 对方公钥
//     * @param content         原文
//     * @param signedString    签文
//     * @return ture-成功；false-失败
//     * @throws Exception
//     */
//    private boolean rsaVerifySign(String publicKeyString, String content, String signedString) throws Exception {
//        KeyFactory keyFactory = KeyFactory.getInstance("RSA", new BouncyCastleProvider());
//        X509EncodedKeySpec bobPubKeySpec = new X509EncodedKeySpec(Base64Utils.decode(publicKeyString, Base64Type.RFC4648));
//        PublicKey publicKey = keyFactory.generatePublic(bobPubKeySpec);
//        Signature verifySign = Signature.getInstance("SHA256WITHRSA");
//        verifySign.initVerify(publicKey);
//        verifySign.update(content.getBytes());
//        return verifySign.verify(Base64Utils.decode(signedString, Base64Type.RFC4648));
//    }

    @Override
    public void fieldMapping(ApiUserRequest apiUserRequest) {
        /** 年龄 */
        String age = apiUserRequest.getAge();
        if (!StringUtils.isEmpty(age)) {
            apiUserRequest.setAge(ApiDictUtils.convertAge(age));
        }

        //  性别
        String sex = apiUserRequest.getSex();
        if (ValidParam.isNotEmpty(sex)) {
            String sexChoose = ChooseEq.create()
                    .when(sex, "1", "0")
                    .when(sex, "2", "1")
                    .end("2");
            apiUserRequest.setSex(sexChoose);
        }

        /**
         * 贷款额度
         * 20万以上=1
         * 10万-20万=2
         * 5万-10万=3
         * 1万-5万=4
         * 1万以内=5
         */
        String loanAmount = apiUserRequest.getLoanAmount();
        String myLoanAmount;
        if (loanAmount != null) {
            switch (loanAmount) {
                case "1":
                    myLoanAmount = "4";
                    break;
                case "2":
                    myLoanAmount = "3";
                    break;
                case "3":
                    myLoanAmount = "2";
                    break;
                case "4":
                case "5":
                    myLoanAmount = "1";
                    break;
                default:
                    myLoanAmount = null;
            }
            apiUserRequest.setLoanAmount(myLoanAmount);
        }

        /**
         * 芝麻分
         * 700分以上=1
         * 650-699分=2
         * 600-649分=3
         * 600分以下=4
         */
        String sesameCredit = apiUserRequest.getSesameCredit();
        String mySesameCredit;
        if (sesameCredit != null) {
            switch (sesameCredit) {
                case "1":
                    mySesameCredit = "4";
                    break;
                case "2":
                    mySesameCredit = "3";
                    break;
                case "3":
                    mySesameCredit = "2";
                    break;
                case "4":
                    mySesameCredit = "1";
                    break;
                default:
                    mySesameCredit = null;
            }
            apiUserRequest.setSesameCredit(mySesameCredit);
        }

        /**
         * 花呗额度
         * 5000元以上=1
         * 5000元以内=2
         * 无花呗额度=3
         */
        String hbLimit = apiUserRequest.getHbLimit();
        String myHbLimit;
        if (hbLimit != null) {
            switch (hbLimit) {
                case "1":
                    myHbLimit = "4";
                    break;
                case "2":
                    myHbLimit = "3";
                    break;
                case "3":
                    myHbLimit = "1";
                    break;
                default:
                    myHbLimit = null;
            }
            apiUserRequest.setHbLimit(myHbLimit);
        }

        /**
         * 白条额度
         * 5000元以上=1
         * 5000元以内=2
         * 无白条额度=3
         */
        String btLimit = apiUserRequest.getBtLimit();
        String myBtLimit;
        if (btLimit != null) {
            switch (btLimit) {
                case "1":
                    myBtLimit = "4";
                    break;
                case "2":
                    myBtLimit = "3";
                    break;
                case "3":
                    myBtLimit = "1";
                    break;
                default:
                    myBtLimit = null;
            }
            apiUserRequest.setBtLimit(myBtLimit);
        }

        /**
         * 信用状况
         * 当前有逾期=1
         * 当前无逾期=2
         */
        String overdue = apiUserRequest.getOverdue();
        String myOverdue;
        if (overdue != null) {
            switch (overdue) {
                case "1":
                    myOverdue = "2";
                    break;
                case "2":
                    myOverdue = "1";
                    break;
                default:
                    myOverdue = null;
            }
            apiUserRequest.setOverdue(myOverdue);
        }

        /**
         * 房产
         * 无房产=0
         * 有房产=1
         */
        String realEstateInfo = apiUserRequest.getRealEstateInfo();
        String myRealEstateInfo;
        if (realEstateInfo != null) {
            switch (realEstateInfo) {
                case "0":
                    myRealEstateInfo = "1";
                    break;
                case "1":
                    myRealEstateInfo = "4";
                    break;
                default:
                    myRealEstateInfo = null;
            }
            apiUserRequest.setRealEstateInfo(myRealEstateInfo);
        }

        /**
         * 车产
         * 无车产=0
         * 有车=1
         */
        String carInfo = apiUserRequest.getCarInfo();
        String myCarInfo;
        if (carInfo != null) {
            switch (carInfo) {
                case "0":
                    myCarInfo = "1";
                    break;
                case "1":
                    myCarInfo = "4";
                    break;
                default:
                    myCarInfo = null;
            }
            apiUserRequest.setCarInfo(myCarInfo);
        }

        /**
         * 公积金
         * 无公积金=0
         * 有公积金=1
         */
        String providentFund = apiUserRequest.getProvidentFund();
        String myProvidentFund;
        if (providentFund != null) {
            switch (providentFund) {
                case "0":
                    myProvidentFund = "1";
                    break;
                case "1":
                    myProvidentFund = "4";
                    break;
                default:
                    myProvidentFund = null;
            }
            apiUserRequest.setProvidentFund(myProvidentFund);
        }

        /**
         * 社保
         * 无社保=0
         * 有社保=1
         */
        String socialSecurity = apiUserRequest.getSocialSecurity();
        String mySocialSecurity;
        if (socialSecurity != null) {
            switch (socialSecurity) {
                case "0":
                    mySocialSecurity = "1";
                    break;
                case "1":
                    mySocialSecurity = "4";
                    break;
                default:
                    mySocialSecurity = null;
            }
            apiUserRequest.setSocialSecurity(mySocialSecurity);
        }
    }


    @Override
    public Object reqPullApplyNotice(ApiReceiveNotice apiNoticeMessage) {
        return null;
    }

    @Override
    public boolean respPullApplyNotice(String responseBody) {
        return false;
    }

    @Override
    public Object reqPushApplyNotice(ApiReceiveNotice apiNoticeMessage) {
        return null;
    }

    @Override
    public boolean respPushApplyNotice(String responseBody) {
        return false;
    }

    public Map<String, Object> getTemp(String orderNum) {
        String JsonString = TEMP.get(orderNum, String.class);
        if (StringUtils.isEmpty(JsonString)) {
            return MapUtils.newLinkedHashMap(dataMap -> {
                dataMap.put("code", "500");
                dataMap.put("msg", "超时");
            });
        }
        JSONObject jsonObject = JsonUtils.get(JsonString);
        String planId = jsonObject.getString("plan_id");
        String companyId = jsonObject.getString("company_id");
        String price = jsonObject.getString("price");
        String company = jsonObject.getString("company");
        String companyName = jsonObject.getString("company_name");
        Map<String, Object> resultMap = MapUtils.newLinkedHashMap();
        resultMap.put("code", "200");
        resultMap.put("msg", "最优匹配的一家下游详情");
        resultMap.put("plan_id", planId);
        resultMap.put("order_num", orderNum);
        resultMap.put("company_id", companyId);
        resultMap.put("xieyi", "");
        resultMap.put("price", price);
        resultMap.put("company", company);
        resultMap.put("company_name", companyName);
        return resultMap;
    }
}
